import {useCallback, useRef, useState} from 'react';
import {View} from 'react-native';
import {WebView} from 'react-native-webview';
import Spinner from 'react-native-loading-spinner-overlay';
import NfcManager, {NfcTech} from 'react-native-nfc-manager';
import {getStorageItem, setStorageItem} from 'utils/storage';
import {useFocusEffect} from '@react-navigation/native';
import {Props} from 'types/global';
export default (props: Props<'create'>) => {
  const [visible, setVisible] = useState(false);
  const webViewRef = useRef<WebView>(null);
  const [list, setList] = useState('');
  async function readNdef(image: string, type: number) {
    try {
      await NfcManager.requestTechnology(NfcTech.IsoDep);
      const tag = await NfcManager.getTag();
      if (tag) {
        NfcManager.sendPicture(image, type);
      }
    } catch (e) {
      console.log('error:' + e);
    } finally {
      setVisible(false);
      NfcManager.cancelTechnologyRequest();
    }
  }
  useFocusEffect(
    useCallback(() => {
      getStorageItem('dragData').then(value => {
        const currentValue = value ?? JSON.stringify([]);
        let currentList =
          props.route?.params?.index >= 0
            ? JSON.stringify({
                index: props.route?.params?.index,
                data: JSON.parse(currentValue),
              })
            : currentValue;
        webViewRef.current?.postMessage(currentValue);
        setList(currentList);
      });
    }, []),
  );
  return (
    <View style={{flex: 1}}>
      <Spinner
        visible={visible}
        color="#409EFF"
        textContent="同步中,请稍候"
        textStyle={{
          fontSize: 14,
          color: '#409EFF',
        }}></Spinner>
      <WebView
        allowFileAccess={true}
        domStorageEnabled
        startInLoadingState
        ref={webViewRef}
        allowUniversalAccessFromFileURLs
        cacheEnabled={true}
        originWhitelist={['*']}
        setBuiltInZoomControls={false}
        setDisplayZoomControls={false}
        // @ts-ignore
        blobDownloadingEnabled
        onLoadEnd={() => {
          webViewRef.current?.postMessage(list);
        }}
        source={{uri: 'file:///android_asset/index.html'}}
        allowFileAccessFromFileURLs={true}
        onMessage={event => {
          if (event.nativeEvent.data === 'loading') {
            setVisible(true);
          } else if (event.nativeEvent.data.includes('同步')) {
            readNdef(
              'file:///data/user/0/com.awesomeproject/files/' +
                event.nativeEvent.data.slice(2),
              0,
            );
          } else if (event.nativeEvent.data.includes('模板')) {
            setStorageItem('dragData', event.nativeEvent.data.slice(2));
          }
          // setUrl(event.nativeEvent.data);
        }}
        style={{flex: 1}}></WebView>
    </View>
  );
};
